﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WorkRecord.CommonClass;

namespace WorkRecord
{
    public partial class WorkView : System.Web.UI.Page
    {
        public DataAccess da = new DataAccess();
        protected void Page_Load(object sender, EventArgs e)
        {
            //判断Session为null
            //to do
            if (!IsPostBack)
            {
                if (WebContext.Current.IsAdministrator)
                {
                    hlAdmin.Visible = true;
                    hlAdmin.NavigateUrl = "/AdminMana/ManaIndex.aspx";
                }
                //string user = ((CDL.DataStruct.UserDetailData.UserDetailStruct)Session[CDL.BPM_Configuration.strUserDetail]).USERNAME_VALUE.ToString();
                //if (!da.JourneyViewPermission(user))
                //{
                //    CDL.Utility.MessageBox.ShowAndClose(this, "您没有权限，请联系系统管理员!");
                //}
                //else
                {
                    InitMajorWork();
                    InitCategory();
                    BindJourneyCategory();
                    //BindRpt(true);
                }
                this.imgbtn_right.Visible = false;
                this.hl.NavigateUrl = "WorkEnter.aspx";
            }
        }

        public void InitMajorWork()
        {
            var dt = da.GetMajorWorj(WebContext.Current.CurrentUser.Rows[0]["username"].ToString());
            if (dt != null && dt.Rows.Count > 0)
            {
                div_FileValue.InnerHtml = dt.Rows[0]["CurrMonthMajorWorkork"].ToString().Replace("\r\n","<br />");
            }
        }

        public void InitCategory()
        {
            DataTable categoryDt;
            da.CanEnter(WebContext.Current.CurrentUser.Rows[0]["username"].ToString(), out categoryDt);
            if (categoryDt != null && categoryDt.Rows.Count > 0)
            {
                ddlJourneyCategory.SelectedValue = categoryDt.Rows[0]["CategoryID"].ToString();
            }
        }

        private void BindRpt(bool CanChange)
        {
            if (this.hf_current_day.Value.Trim() == "")
                this.hf_current_day.Value = DateTime.Today.ToString("yyyy-MM-dd");
            this.lb_today.Text = this.hf_current_day.Value;

            //string user = ((CDL.DataStruct.UserDetailData.UserDetailStruct)Session[CDL.BPM_Configuration.strUserDetail]).USERNAME_VALUE.ToString();
            string user = WebContext.Current.CurrentUser.Rows[0]["username"].ToString();

            DataTable categoryDt;
            string sql =
                string.Format(@"SELECT u.username,u.realname,j.Guid,j.SubmitTime,(case (select count(*) from  JourneyUserPermission where type=2 and UserAccount='{0}' and ViewToUserAccount=t.ViewToUserAccount) when 0 then 0 else 1 end) as canComment
FROM 
(
{3}
SELECT DISTINCT ViewToUserAccount
FROM JourneyUserPermission
inner join T_Sys_User ON T_Sys_User.username=JourneyUserPermission.ViewToUserAccount and T_Sys_User.state=1
WHERE UserAccount='{0}' and ViewToUserAccount<>'{0}' {2}

)t 
LEFT JOIN T_Sys_User u ON u.username=t.ViewToUserAccount
LEFT JOIN Journeys j ON j.UserAccount=t.ViewToUserAccount and CONVERT(varchar(100), SubmitTime, 23)='{1}'",
                    user, this.hf_current_day.Value,
                    string.IsNullOrEmpty(ddlJourneyCategory.SelectedValue)
                        ? string.Empty
                        : string.Format(
                            " and ViewToUserAccount in (select UserAccount from JourneyCategoryUserMapping where CategoryID='{0}')",
                            ddlJourneyCategory.SelectedValue),
                    da.CanEnter(user, ddlJourneyCategory.SelectedValue, out categoryDt)
                        ? string.Format("select '{0}' as ViewToUserAccount union all ", user)
                        : string.Empty);
            DataTable dt = da.readdata(sql);
            rptJourneys.DataSource = dt;
            rptJourneys.DataBind();

            if (CanChange)
            {
                if (dt != null)
                {
                    foreach (DataRow dr in dt.Rows)
                        if (!string.IsNullOrEmpty(dr["SubmitTime"].ToString()) && dr["username"].ToString() == user)
                            this.hl.Text = "修改今日工作日记";
                }
            }

        }

        public string GetCities(string Guid, int IsToDay)
        {
            string returnStr = string.Empty;
            string sql = string.Format(@"select Area from JourneyCities where IsToday={0} and Guid='{1}'", IsToDay, Guid);
            DataTable dt = da.readdata(sql);
            foreach (DataRow dr in dt.Rows)
            {
                returnStr += dr["Area"].ToString() + ",";
            }
            return returnStr.Trim(',');
        }

        public string GetContents(string Guid)
        {
            string resultStr = string.Empty;
            string sql = string.Format(@"select * from JourneyContents where Guid='{0}'", Guid);
            DataTable dt = da.readdata(sql);
            /*if (dt.Rows.Count != 0)
                resultStr = "<hr/>";
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                if (i != dt.Rows.Count - 1)
                    resultStr += @"<p>" + dt.Rows[i]["StartHour"].ToString() + " - " + dt.Rows[i]["EndHour"].ToString() + " &nbsp;&nbsp; " + dt.Rows[i]["WorkType"] + "</p><p>" + dt.Rows[i]["Contents"] + "</p><p>----------------------------------</p>";
                else
                    resultStr += @"<p>" + dt.Rows[i]["StartHour"].ToString() + " - " + dt.Rows[i]["EndHour"].ToString() + " &nbsp;&nbsp; " + dt.Rows[i]["WorkType"] + "</p><p>" + dt.Rows[i]["Contents"] + "</p>";
            }
            return resultStr;*/
            System.Text.StringBuilder c = new System.Text.StringBuilder();
            string[] number = { "① ", "② ", "③ ", "④ ", "⑤ ", "⑥ ", "⑦ ", "⑧ ", "⑨ ", "⑩ ", "○ " };
            if (dt.Rows.Count != 0)
            {
                int i = 0;
                foreach (DataRow dr in dt.Rows)
                {
                    if (i < number.Length)
                        c.Append(number[i]);
                    else
                        c.Append("○ ");
                    i++;
                    c.Append(dr["starthour"].ToString() + "-" + dr["endhour"].ToString() + " ");
                    c.Append(dr["worktype"].ToString() + "：");
                    c.Append(dr["contents"].ToString() + "<br/>");
                }
            }
            return c.ToString();
        }

        public string GetCategory(string username)
        {
            var sql = string.Format(@"SELECT * 
                                    FROM JourneyCategoryUserMapping m
                                    INNER JOIN JourneyCategory j ON m.CategoryID=j.ID
                                    WHERE m.UserAccount='{0}'", username);
            var dt = da.readdata(sql);
            var sb = new StringBuilder();
            if (dt == null || dt.Rows.Count <= 0) return sb.ToString().Trim(';');
            foreach (DataRow dr in dt.Rows)
            {
                sb.Append(dr["CategoryName"]+";");
            }
            return sb.ToString().Trim(';');
        }

        public string GetComments(string guid)
        {
            if (string.IsNullOrEmpty(guid)) return string.Empty;
            var sql = string.Format(@"select JourneyComments.*,T_Sys_User.realname from JourneyComments inner join T_Sys_User on JourneyComments.CreateBy=T_Sys_User.username where Guid='{0}' order by JourneyComments.ID asc", guid);
            var dt = da.readdata(sql);
            var sb = new StringBuilder();
            if (dt == null || dt.Rows.Count <= 0) return sb.ToString();
            for (var i = 0; i < dt.Rows.Count; i++)
            {
                if (i != dt.Rows.Count - 1)
                {
                    sb.Append(dt.Rows[i]["realname"] + "：" + dt.Rows[i]["Comment"] + "<br />");
                }
                else
                {
                    sb.Append(dt.Rows[i]["realname"] + "：" + dt.Rows[i]["Comment"]);
                }
            }
            return sb.ToString();
        }

        protected void imgbtn_left_Click(object sender, ImageClickEventArgs e)
        {
            DateTime t = DateTime.Parse(this.hf_current_day.Value);
            DateTime yesterday = t.AddDays((double)-1);
            this.hf_current_day.Value = yesterday.ToString("yyyy-MM-dd");
            BindRpt(false);
            this.imgbtn_right.Visible = true;
        }

        protected void imgbtn_right_Click(object sender, ImageClickEventArgs e)
        {
            DateTime t = DateTime.Parse(this.hf_current_day.Value);
            DateTime tomorrow = t.AddDays((double)1);
            this.hf_current_day.Value = tomorrow.ToString("yyyy-MM-dd");
            BindRpt(false);
            if (tomorrow == System.DateTime.Today)
                this.imgbtn_right.Visible = false;
        }

        protected void imgbtn_left_Click1(object sender, EventArgs e)
        {
            DateTime t = DateTime.Parse(this.hf_current_day.Value);
            DateTime yesterday = t.AddDays((double)-1);
            this.hf_current_day.Value = yesterday.ToString("yyyy-MM-dd");
            BindRpt(false);
            this.imgbtn_right.Visible = true;
        }

        protected void imgbtn_right_Click1(object sender, EventArgs e)
        {
            DateTime t = DateTime.Parse(this.hf_current_day.Value);
            DateTime tomorrow = t.AddDays((double)1);
            this.hf_current_day.Value = tomorrow.ToString("yyyy-MM-dd");
            BindRpt(false);
            if (tomorrow == System.DateTime.Today)
                this.imgbtn_right.Visible = false;
        }

        protected void ShowJourneyEnter()
        {
            DataTable categoryDt;
            if (da.CanEnter(WebContext.Current.CurrentUser.Rows[0]["username"].ToString(),out categoryDt))
                hl.Visible = true;
            else
                hl.Visible = false;

        }

        private void BindJourneyCategory()
        {
            DataTable dt = da.readdata("SELECT * FROM JourneyCategory ORDER BY [SORT]");
            ddlJourneyCategory.DataSource = dt;
            ddlJourneyCategory.DataTextField = "CategoryName";
            ddlJourneyCategory.DataValueField = "ID";
            ddlJourneyCategory.DataBind();
            ddlJourneyCategory.Items.Insert(0, new ListItem("--请选择--", string.Empty));

            ShowJourneyEnter();
            BindRpt(true);
        }

        protected void ddlJourneyCategory_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.hf_current_day.Value = DateTime.Today.ToString("yyyy-MM-dd");
            ShowJourneyEnter();

            BindRpt(true);
            this.imgbtn_right.Visible = false;
        }

        protected void rptJourneys_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "save")
            {
                string user = WebContext.Current.CurrentUser.Rows[0]["username"].ToString();
                var hfGuid = e.Item.FindControl("hfGuid") as HiddenField;
                var comment = e.Item.FindControl("txtComment") as TextBox;

                var isexisDt = GetComment(hfGuid.Value, user);
                if (isexisDt != null && isexisDt.Rows.Count > 0)
                {
                    var paras = new SqlParameter[3];
                    paras[0] = new SqlParameter("@ID", isexisDt.Rows[0]["ID"]);
                    paras[1] = new SqlParameter("@Comment", comment.Text);
                    paras[2] = new SqlParameter("@LastModifyTime", DateTime.Now);
                    da.datacmd(
                        "update JourneyComments set Comment=@Comment,LastModifyTime=@LastModifyTime where ID=@ID", paras);
                }
                else
                {
                    var paras = new SqlParameter[4];
                    paras[0] = new SqlParameter("@Guid", hfGuid.Value);
                    paras[1] = new SqlParameter("@Comment", comment.Text);
                    paras[2] = new SqlParameter("@CreateBy", user);
                    paras[3] = new SqlParameter("@LastModifyTime", DateTime.Now);

                        string sql =
                            "insert into JourneyComments(Guid,Comment,CreateBy,LastModifyTime) values(@Guid,@Comment,@CreateBy,@LastModifyTime)";
                    da.datacmd(sql, paras);
                }
            }
            BindRpt(true);
        }

        protected void rptJourneys_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            var item = e.Item.DataItem;

            var guid = (e.Item.FindControl("hfGuid") as HiddenField).Value;
            var submitTime = (e.Item.FindControl("hfSubmitTime") as HiddenField).Value;
            var txtComment = e.Item.FindControl("txtComment") as TextBox;
            var btnSave = e.Item.FindControl("btnSave") as Button;

            if (string.IsNullOrEmpty(submitTime))
            {
                //lb_today.Text != DateTime.Now.ToString("yyyy-MM-dd") || 
                btnSave.Visible = txtComment.Visible = false;
            }
            else
            {
                if ((e.Item.FindControl("hfCanComment") as HiddenField).Value == "1")
                {
                    btnSave.Visible = txtComment.Visible = true;
                    string user = WebContext.Current.CurrentUser.Rows[0]["username"].ToString();
                    var isexisDt = GetComment(guid, user);
                    if (isexisDt != null && isexisDt.Rows.Count > 0)
                    {
                        btnSave.Text = "编辑";
                        txtComment.Text = isexisDt.Rows[0]["Comment"].ToString();
                    }
                    else
                    {
                        btnSave.Text = "提交";
                    }
                }
                else
                {
                    btnSave.Visible = txtComment.Visible = false;
                }
            }

            
        }

        private DataTable GetComment(string guid,string username)
        {
            if (string.IsNullOrEmpty(guid)) return null;
            return
                da.readdata(string.Format("select * from JourneyComments where Guid='{0}' and CreateBy='{1}'",
                    guid, username));
        }

        public string GetLastModifyTime(string guid,string submitTime)
        {
            if (string.IsNullOrEmpty(guid)) return string.Empty;

            var dt =
                da.readdata(string.Format(
                    "SELECT * FROM JourneyComments where Guid='{0}' order by LastModifyTime DESC", guid));
            if (dt != null && dt.Rows.Count > 0)
            {
                return dt.Rows[0]["LastModifyTime"].ToString();
            }
            return submitTime;
        }

        public string GetMajorWork(string user)
        {
            var dt = da.GetMajorWorj(user);
            var sb = new StringBuilder();
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (var str in dt.Rows[0]["CurrMonthMajorWorkork"].ToString().Replace("\r\n", "￥").Split('￥'))
                {
                    sb.AppendFormat("<li>{0}</li>", str);
                }

            }
            return sb.ToString();
        }
        
    }
}